package com.osmino.contacts.groups.add;

import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckedTextView;
import android.widget.TextView;
import com.osmino.contacts.R;
import com.osmino.contacts.entity.LocalAccount;

public final class AccountAdapter extends BaseAdapter {

	private final Context mContext;
	private final List<LocalAccount> mListAccounts;
	private static final int TWO_LINE_TYPE = 0;
	private static final int ONE_LINE_TYPE = 1;

	public AccountAdapter(Context context) {
		mContext = context;
		mListAccounts = new ArrayList<LocalAccount>();
	}

	@Override
	public int getViewTypeCount() {
		return 2;
	}

	@Override
	public int getItemViewType(int position) {
		int viewType = TWO_LINE_TYPE;
		if (getItem(position).isPhoneAccount()) {
			viewType = ONE_LINE_TYPE;
		}
		return viewType;
	}

	@Override
	public int getCount() {
		return mListAccounts.size();
	}

	@Override
	public LocalAccount getItem(int position) {
		return mListAccounts.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View view = convertView;
		if (view == null) {
			view = newView(position, parent);
		}
		bindView(position, view);
		return view;
	}

	private View newView(int position, ViewGroup parent) {
		int viewType = getItemViewType(position);
		View view = null;
		if (viewType == TWO_LINE_TYPE) {
			view = new TwoLineListItemCheckable(mContext);
		} else if (viewType == ONE_LINE_TYPE) {
			TextView textView = (TextView) LayoutInflater.from(mContext).inflate(
					android.R.layout.simple_list_item_single_choice, parent, false);
			textView.setTextColor(Color.BLACK);
			textView.setTypeface(Typeface.DEFAULT);
			textView.setPadding(30, 0, 0, 0);
			view = textView;
		}
		return view;
	}

	private void bindView(int position, View view) {
		int viewType = getItemViewType(position);
		LocalAccount account = mListAccounts.get(position);
		if (viewType == TWO_LINE_TYPE) {
			TwoLineListItemCheckable twoLineView = (TwoLineListItemCheckable) view;
			twoLineView.setText1(account.type);
			twoLineView.setText2(account.name);
		} else if (viewType == ONE_LINE_TYPE) {
			CheckedTextView oneLineView = (CheckedTextView) view;
			oneLineView.setText(R.string.phone);
		}
	}

	public void setListAccounts(List<LocalAccount> listAccounts) {
		mListAccounts.clear();
		mListAccounts.addAll(listAccounts);
		notifyDataSetChanged();
	}

}
